package com.sunjob.loginserver.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.sunjob.common.constant.MROConstant;
import com.sunjob.common.domain.img.SysImg;
import com.sunjob.common.domain.loginServer.SysUser;
import com.sunjob.common.result.Result;
import com.sunjob.common.util.MROUtils;
import com.sunjob.loginserver.otherService.ImgService;
import com.sunjob.loginserver.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-08-24 11:09
 */
@Api(value = "用户操作api", tags = "用户操作api")
@RestController
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ImgService imgService;
    @ApiOperation("新增用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户实体", paramType = "body")
    })
    @PostMapping("/addUser")
    public Result<Boolean> addUser(@RequestBody SysUser user, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        Map<String, Object> params = user.getParams();
        if (params == null || params.size() == 0) {
            return Result.fail("验证码错误");
        }
        String code = (String) params.get("code");

        if (code == null) {
            return Result.fail("验证码错误");
        }
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        String o = (String) stringObjectValueOperations.get(MROConstant.CODES + ":" + remoteAddr);
        if (o == null || !o.toLowerCase().equals(code.toLowerCase())) {
            return Result.fail("验证码错误");
        }
        // 新增用户
        // 检查登录名
        if (user.getLoginName() == null || user.getLoginName().trim().length() == 0) {
            return Result.fail("登录名不能为空");
        }
        // 用户名进行随机
        // 检查用户密码
        if (user.getPassword() == null || user.getPassword().trim().length() == 0) {
            return Result.fail("用户密码不能为空");
        }
        // 检查手机号
        if (user.getPhonenumber() == null || user.getPhonenumber().trim().length() == 0) {
            return Result.fail("用户手机号不能为空");
        }
        // 检查邮箱
        if (user.getEmail() == null || user.getEmail().trim().length() == 0) {
            return Result.fail("用户邮箱不能为空");
        }
        // 设置默认角色 common
        String temp = "";
        if (!(temp = MROUtils.verifyUser(user)).equals("success")) {
            return Result.fail(temp);
        }
        Integer i = userService.addUser(user);
        if (i == 0) {
            return Result.fail("注册用户失败");
        }
        return Result.ok(true, "注册成功");
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/updateUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "satoken", value = "token", paramType = "header"),
            @ApiImplicitParam(name = "user", value = "用户信息", paramType = "body")
    })
    public Result<Boolean> updateUser(@RequestBody SysUser user) {
        // 只允许修改 手机号码 用户名 邮箱 性别
        return userService.udpateUser(user);
    }

    @ApiOperation("修改用户头像")
    @PostMapping("/updateAvatar")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "satoken",value = "token",paramType = "header"),
            @ApiImplicitParam(name = "avatar",value = "头像",paramType = "query")
    })
    public Result<SysImg> updateAvatar(@RequestParam("avatar")MultipartFile img) throws Exception{
        // 修改用户头像
        // 获取字节数组
        byte[] bytes = img.getBytes();
        String fileName = img.getOriginalFilename();
        SysImg sysImg = new SysImg();
        sysImg.setData(bytes);
        // 获取后缀名
        String[] split = fileName.split("\\.");
        try {
            String suff = split[split.length-1];
            sysImg.setImgUrl("loginServer/"+ UUID.randomUUID()+"."+suff);
        }catch (Exception e){
            return Result.fail("图片名含有非法字符");
        }
        Long loginId = StpUtil.getLoginIdAsLong();
        // 修改用户头像
        SysImg sysImg1 = userService.udpateAvatar(loginId,sysImg);
        if(sysImg1==null){
            return Result.fail("修改用户头像失败");
        }
        SaSession tokenSession = StpUtil.getTokenSession();
        SysUser user = (SysUser)tokenSession.get("userInfo");
        user.setAvatarUrl(sysImg1.getAbImgUrl());
        tokenSession.set("userInfo",user);
        return Result.ok(sysImg1,"修改头像成功");
    }


}
